package com.aqie.juc.atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.stream.IntStream;

/**
 * 描述：     演示LongAccumulator的用法
 */
public class LongAccumulatorDemo {

    public static void main(String[] args) {
        // test();
        test2();
    }

    private static void test2() {
        // LongAccumulator accumulator = new LongAccumulator((x, y) -> 2 + x * y, 1);
        LongAccumulator accumulator = new LongAccumulator((x, y) -> x + y, 0);  // 从 1 ... 9 = 45
        ExecutorService executor = Executors.newFixedThreadPool(8);
        IntStream.range(1, 10).forEach(i -> executor.submit(() -> accumulator.accumulate(i)));

        executor.shutdown();
        while (!executor.isTerminated()) {

        }
        System.out.println(accumulator.getThenReset());
    }

    public static void test() {
        // 开始 x = 1, 原来结果1 = y  1 + 2 + 1 = 4  数学归纳
        LongAccumulator accumulator = new LongAccumulator((x, y) -> x + y, 1);
        accumulator.accumulate(2);
        accumulator.accumulate(1);
        System.out.println(accumulator.getThenReset()); // 4
    }
}
